package net.cyue.util;

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class UnicodeUtil {
    // 转义字符映射表
    private static final Map<Character, Character> ESCAPE_MAP = new HashMap<>();
    static {
        ESCAPE_MAP.put('n', '\n');
        ESCAPE_MAP.put('t', '\t');
        ESCAPE_MAP.put('r', '\r');
        ESCAPE_MAP.put('b', '\b');
        ESCAPE_MAP.put('f', '\f');
        ESCAPE_MAP.put('\'', '\'');
        ESCAPE_MAP.put('"', '"');
        ESCAPE_MAP.put('\\', '\\');
    }

    /**
     * 将包含转义序列的字符串转换为普通字符串
     * @param escapedStr 包含转义序列的字符串
     * @return 转换后的普通字符串
     */
    public static String unescape(String escapedStr) {
        if (escapedStr == null || escapedStr.isEmpty()) {
            return escapedStr;
        }

        StringBuilder sb = new StringBuilder();
        int length = escapedStr.length();
        for (int i = 0; i < length; ) {
            char currentChar = escapedStr.charAt(i);
            if (currentChar == '\\' && i + 1 < length) {
                char nextChar = escapedStr.charAt(i + 1);

                // 处理Unicode转义序列(\\uXXXX)
                if (nextChar == 'u' && i + 5 < length) {
                    try {
                        String hex = escapedStr.substring(i + 2, i + 6);
                        int codePoint = Integer.parseInt(hex, 16);
                        sb.append((char) codePoint);
                        i += 6;
                        continue;
                    } catch (NumberFormatException e) {
                        // 如果不是有效的十六进制数，保持原样
                    }
                }

                // 处理十六进制转义序列(\\xXX)
                if (nextChar == 'x' && i + 3 < length) {
                    try {
                        String hex = escapedStr.substring(i + 2, i + 4);
                        int codePoint = Integer.parseInt(hex, 16);
                        sb.append((char) codePoint);
                        i += 4;
                        continue;
                    } catch (NumberFormatException e) {
                        // 如果不是有效的十六进制数，保持原样
                    }
                }

                // 处理其他转义序列
                if (ESCAPE_MAP.containsKey(nextChar)) {
                    sb.append(ESCAPE_MAP.get(nextChar));
                    i += 2;
                    continue;
                }
            }
            sb.append(currentChar);
            i++;
        }
        return sb.toString();
    }

    /**
     * 使用正则表达式方式将转义序列转换为普通字符串
     * @param escapedStr 包含转义序列的字符串
     * @return 转换后的普通字符串
     */
    public static String unescapeByRegex(String escapedStr) {
        if (escapedStr == null || escapedStr.isEmpty()) {
            return escapedStr;
        }

        // 匹配Unicode转义序列(\\uXXXX)
        Pattern unicodePattern = Pattern.compile("\\\\u([0-9a-fA-F]{4})");
        Matcher unicodeMatcher = unicodePattern.matcher(escapedStr);
        StringBuffer sb = new StringBuffer();

        while (unicodeMatcher.find()) {
            String group = unicodeMatcher.group(1);
            char ch = (char) Integer.parseInt(group, 16);
            unicodeMatcher.appendReplacement(sb, String.valueOf(ch));
        }
        unicodeMatcher.appendTail(sb);

        // 匹配十六进制转义序列(\\xXX)
        String intermediateResult1 = sb.toString();
        sb = new StringBuffer();
        Pattern hexPattern = Pattern.compile("\\\\x([0-9a-fA-F]{2})");
        Matcher hexMatcher = hexPattern.matcher(intermediateResult1);

        while (hexMatcher.find()) {
            String group = hexMatcher.group(1);
            char ch = (char) Integer.parseInt(group, 16);
            hexMatcher.appendReplacement(sb, String.valueOf(ch));
        }
        hexMatcher.appendTail(sb);

        // 处理其他转义序列
        String intermediateResult2 = sb.toString();
        sb = new StringBuffer();
        Pattern escapePattern = Pattern.compile("\\\\([nrtbf'\"\\\\])");
        Matcher escapeMatcher = escapePattern.matcher(intermediateResult2);

        while (escapeMatcher.find()) {
            char escapeChar = escapeMatcher.group(1).charAt(0);
            char replacement = ESCAPE_MAP.get(escapeChar);
            escapeMatcher.appendReplacement(sb, String.valueOf(replacement));
        }
        escapeMatcher.appendTail(sb);

        return sb.toString();
    }

    /**
     * 将普通字符串转换为转义序列形式
     * @param str 普通字符串
     * @return 包含转义序列的字符串
     */
    public static String escape(String str) {
        if (str == null || str.isEmpty()) {
            return str;
        }

        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < str.length(); i++) {
            char c = str.charAt(i);
            switch (c) {
                case '\n': sb.append("\\n"); break;
                case '\t': sb.append("\\t"); break;
                case '\r': sb.append("\\r"); break;
                case '\b': sb.append("\\b"); break;
                case '\f': sb.append("\\f"); break;
                case '\'': sb.append("\\'"); break;
                case '"': sb.append("\\\""); break;
                case '\\': sb.append("\\\\"); break;
                default:
                    if (c <= 31 || c >= 127) {
                        // 优先使用短格式的十六进制转义(\xXX)如果可能
                        if (c <= 0xFF) {
                            sb.append(String.format("\\x%02x", (int) c));
                        } else {
                            sb.append(String.format("\\u%04x", (int) c));
                        }
                    } else {
                        sb.append(c);
                    }
            }
        }
        return sb.toString();
    }
}